package com.pagepub.core.tag.message;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pagepub.core.utils.ActionMessage;
import com.pagepub.core.utils.ActionMessages;

/**
 * 验证框架通不过返回的错误信息标签
 * 
 * @author ggd
 * 
 */
@SuppressWarnings("serial")
public class MessageTag extends TagSupport {
	private String name = ActionMessages.class.getName();

	private String property;

	private Log log = LogFactory.getLog(MessageTag.class);

	private final String spanBegin = "<span id=\"validate.msg.xxx\" style=\"COLOR: red\">";

	private final String spanEnd = "</span>";

	public int doStartTag() throws JspException {

		try {
			ActionMessages ams = (ActionMessages) this.pageContext.getRequest()
					.getAttribute(name);
			if (ams == null) {
				this.pageContext.getOut().print(
						spanBegin.replaceAll("xxx", property) + spanEnd);
				return 1;
			}
			Map<String, ActionMessage> m = ams.getMsglist();
			ActionMessage am = null;
			if (property != null && property.length() > 0) {
				am = m.get(property);
				if (am != null) {
					this.pageContext.getOut().print(
							spanBegin.replaceAll("xxx", property)
									+ am.getMessages().replaceAll("\n", "")
									+ spanEnd);
				} else {
					this.pageContext.getOut().print(
							spanBegin.replaceAll("xxx", property) + spanEnd);
				}
			} else {
				String str = "";
				Iterator it = m.keySet().iterator();
				while (it.hasNext()) {
					ActionMessage element = (ActionMessage) m.get(it.next());
					str += element.getMessages().replaceAll("\n", "<br>");
				}
				this.pageContext.getOut().print(
						spanBegin
								.replaceAll("xxx", (new Date()).getTime() + "")
								+ str + spanEnd);
			}
		} catch (IOException e) {
			log.error("MessageTagMessageTag.doStartTag()==>MessageTag标签出错!", e);
			throw new JspException("MessageTag标签出错!", e);
		}
		return 1;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}
}
